package com.jianxun.im

import android.util.Log
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

// 每次冷启动获取一次HttpConfig
class HttpConfigManager(private val callback: (String) -> Unit) {
    companion object {
        private const val CONFIG_URL = "https://dz-json1120.oss-cn-hongkong.aliyuncs.com/app_config.json"
    }

    private val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .build()

    private var cachedConfig: JSONObject? = null

    @Throws(IOException::class, JSONException::class)
    fun fetchAndCacheConfig() {
        val request = Request.Builder()
            .url(CONFIG_URL)
            .build()

        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                Log.e("HttpCache", "onFailure: ${e.message}", )
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    if (!response.isSuccessful) throw IOException("Unexpected code $response")
                    val jsonData = response.body?.string() ?: throw IOException("Empty response body")
                    cachedConfig = JSONObject(jsonData)

                    getBaseUrl().takeIf { it.isNotEmpty() }?.let(callback)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        })
    }

    @Throws(IOException::class, JSONException::class)
    private fun getBaseUrl(): String {
        return cachedConfig?.let {
            val host = it.getString("host")
            val ssl = it.getBoolean("ssl")

            buildUrl(host, ssl)
        }?: ""
    }

    private fun buildUrl(host: String, ssl: Boolean): String {
        val protocol = if (ssl) "https" else "http"
        return "$protocol://$host"
    }
}
